from flask import render_template, current_app, session, jsonify, request, g

from info import redis_store, constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return: 
    """

    # 获取参数
    # 新闻分类id
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)

    # 查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    news_li = paginate.items  # page pages items
    news_dict_list = []
    for news in news_li:
        news_dict_list.append(news.to_basic_dict())

    data = {
        "total_page": paginate.total,
        "current_page": paginate.page,
        "news_dict_list": news_dict_list
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blu.route('/')
@user_login_data
def index():
    """
    显示首页
    1. 用户已经登录，将当前登录用户的数据传到模板中
    :return: 
    """

    user = g.user

    # 右侧新闻排行的逻辑
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict = []
    for news in news_list:
        news_dict.append(news.to_basic_dict())

    # 查询新闻分类数据
    categories = Category.query.all()
    category_li = []
    for c in categories:
        category_li.append(c.to_dict())

    data = {
        "user": user.to_dict() if user else None,
        "news_dict": news_dict,
        "category_li": category_li
    }

    return render_template("news/index.html", data=data)


@index_blu.route('/favicon.ico')
def favicon():
    # send_static_file 是flask查找指定静态文件所调用的方法
    return current_app.send_static_file('news/favicon.ico')
